package setting

import (
	"log"
	"time"

	"github.com/go-ini/ini"
)

type AccServer struct {
	Name    string
	RunMode string
	Host    string
}

var AccServerSetting = &AccServer{}

type Database struct {
	Type        string
	User        string
	Password    string
	Host        string
	Name        string
	TablePrefix string
}

var DatabaseSetting = &Database{}

type RpcServer struct {
	Name    string
	RunMode string
	Host    string
}

var RpcServerSetting = &RpcServer{}

type Redis struct {
	Host        string
	DB          int
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &Redis{}

type RedisCluster struct {
	Host        []string
	DB          int
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisClusterSetting = &RedisCluster{}

type Zookeeper struct {
	Host            string
	AccServerCenter string
	RpcServerCenter string
}

var ZookeeperSetting = &Zookeeper{}

var cfg *ini.File

// Setup initialize the configuration instance
func Init() {
	var err error
	cfg, err = ini.Load("setting/app.ini")
	if err != nil {
		log.Fatalf("setting.Setup, fail to parse 'app.ini': %v", err)
	}

	mapTo("acc server", AccServerSetting)
	mapTo("database", DatabaseSetting)
	mapTo("rpc server", RpcServerSetting)
	mapTo("redis", RedisSetting)
	mapTo("redis cluster", RedisClusterSetting)
	mapTo("zookeeper", ZookeeperSetting)

	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
	RedisClusterSetting.IdleTimeout = RedisClusterSetting.IdleTimeout * time.Second
}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
	}
}
